package com.dragon.dragonshop.component;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

public class RememberMeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if(cookies!=null&&cookies.length>0){
            String rememberName = "";
            String rememberPass = "";
            for (Cookie cookie:cookies){
                if("rememberName".equals(cookie.getName())){
                    rememberName = URLDecoder.decode(cookie.getValue(),"UTF-8");
                }
                if ("rememberPass".equals(cookie.getName())){
                    rememberPass = cookie.getValue();
                }
            }
            if (!StringUtils.isEmpty(rememberName)&&!StringUtils.isEmpty(rememberPass)) {


                request.getSession().setAttribute("user", rememberName);

            }

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
